﻿using RndMaterialDisposalService.Models.RequestModel;
using ValidationProblemTracking.Models;
using ValidationProblemTracking.Services.Interface.ValidationProblemTracking;
using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Services.Interface.SmallBatchTrial;
using Microsoft.Data.SqlClient;
using RndMaterialDisposalService.Models;
using Microsoft.EntityFrameworkCore;
using RndMaterialDisposalService.Repository;
using System.Linq;
using Masuit.Tools;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Agile;
using RndMaterialDisposalService.Extensions;
using NPOI.XWPF.UserModel;
using RndMaterialDisposalService.Helper;
using Razor.Templating.Core;
using Masuit.Tools.Models;
using System.Collections.Generic;

namespace ValidationProblemTracking.Services.ValidationProblemTracking
{
    [NAutowired(Lifecycle.Scoped)]
    public class ValidationProblemService : IValidationProblemService
    {
        private readonly AssetsManagementContext dbContext;
        private readonly UserBaseInforDataContext userBaseInforDataContext;
        private readonly WorkflowCommonDataContext workflowCommonDataContext;
        private IConfiguration configuration;

        private readonly string encyptUserInfo = "/api/UserLoginInforDecrypt/Encypt";
        private readonly string MailSendUrl = "/api/MailSender/SendMailToQueue";

        public ValidationProblemService(AssetsManagementContext _dbContext, UserBaseInforDataContext _userBaseInforDataContext, WorkflowCommonDataContext _workflowCommonDataContext, IConfiguration _configuration) 
        {
            dbContext = _dbContext;
            userBaseInforDataContext = _userBaseInforDataContext;
            workflowCommonDataContext = _workflowCommonDataContext;
            configuration = _configuration;
        }

        /// <summary>
        /// 返回中试验证问题处理电子流报表数据（带分页）
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public List<ValidationProblemReportFormModel> GetValidationProblemReportFormPageList(ValidationProblemReportConditionModel Input) 
        {
            List<ValidationProblemReportFormModel> list = new List<ValidationProblemReportFormModel>();
            List<SqlParameter> sqlParameters = new List<SqlParameter>();
            var eFExtension = new EFExtension();

            string condition = "1=1 ";

            if (!string.IsNullOrWhiteSpace(Input.ProcessFolio))
            {
                condition += $"AND V.ApplicationNumber LIKE '%{Input.ProcessFolio}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.VerifyStartFolio))
            {
                condition += $"AND V.VerifyStartFolio LIKE '%{Input.VerifyStartFolio}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.ProductLine))
            {
                condition += $"AND V.ProductLine LIKE '%{Input.ProductLine}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.ProjectName))
            {
                condition += $"AND V.ProjectName LIKE '%{Input.ProjectName}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.Applicant))
            {
                condition += $"AND V.SubmitByID = '{Input.Applicant}' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.ApplicantDate))
            {
                string[] timeArr = Input.ApplicantDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND V.ApplicantDate >= '{timeArr[0]} 00:00:00' AND V.ApplicantDate <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(Input.CurrentStatus))
            {
                condition += $"AND V.CurrentStatus = '{Input.CurrentStatus}' ";
            }

            //if (!string.IsNullOrWhiteSpace(input.AssetNo))
            //{
            //    condition += $"AND V.AssetNo LIKE '%'+@AssetNo+'%' ";
            //    SqlParameter sqlPara = new SqlParameter("@AssetNo", SqlDbType.NVarChar);
            //    sqlPara.Value = input.AssetNo;
            //    sqlParameters.Add(sqlPara);
            //}

            string SqlInsertClip = string.Empty;

            List<WorkflowProcInstIdModel> ProcInstIdList = new List<WorkflowProcInstIdModel>();

            //获取当前用户电子流审批流程记录,去重后联查得到ProcInstId
            string _sql = $"SELECT a.ProcInstId,c.ApplicationNumber,c.ApproveDate,c.ApproverName FROM ValidationProblemTracking.dbo.ValidationProblemBusinessData a LEFT JOIN (SELECT DISTINCT(ApplicationNumber),(SELECT MIN(ApproveDate) FROM VW_Common.dbo.WorkflowApproveData WHERE ApplicationNumber = b.ApplicationNumber AND WorkflowName = '中试验证问题处理电子流')  AS ApproveDate,ApproverName FROM VW_Common.dbo.WorkflowApproveData b WHERE WorkflowName = '中试验证问题处理电子流') c ON c.ApplicationNumber = a.ProcessFolio WHERE ProcInstId !='' AND ApproveDate IS NOT NULL";
            ProcInstIdList = eFExtension.SqlQuery<WorkflowProcInstIdModel>(dbContext, _sql, new List<SqlParameter>());

            //插入当前用户查询业务
            if (!string.IsNullOrWhiteSpace(Input.CurrentUser))
            {
                ProcInstIdList = ProcInstIdList.Where(a => a.ApproverName == Input.CurrentUser).ToList();
                //审批历史ProcInstId
                var ApprovalHistoryProcInstIdList = ProcInstIdList.Select(a => a.ProcInstId).ToList();

                //当前用户工号
                string employeeNumber = Input.CurrentUser.Substring(0, Input.CurrentUser.IndexOf(" "));
                //利用UserID获取当前用户工号LaunchList
                //var EmployeeInfo = userBaseInforDataContext.UserBaseInfor.FirstOrDefault(x => x.UserId == UserId);
                if (!string.IsNullOrWhiteSpace(employeeNumber))
                {
                    //获取发起流程实例
                    _sql = $"SELECT ProcInstId FROM VW_Common.dbo.WorkflowApplicationData WHERE ProcInstId !='' AND WorkflowName='中试验证问题处理电子流' AND ApplicantEmployeeNumber = '{employeeNumber}'";
                    List<WorkflowProcInstIdModel> LaunchList = eFExtension.SqlQuery<WorkflowProcInstIdModel>(dbContext, _sql, new List<SqlParameter>());
                    if (LaunchList.Any())
                    {
                        var LaunchProcInstIdList = LaunchList.Select(a => a.ProcInstId).ToList();
                        ApprovalHistoryProcInstIdList.AddRange(LaunchProcInstIdList);
                        ApprovalHistoryProcInstIdList = ApprovalHistoryProcInstIdList.Distinct().ToList();
                    }
                }

                string ProcInstId_STR = "''";
                if (ApprovalHistoryProcInstIdList.Any())
                {
                    List<string> _ProcInstIdList = ApprovalHistoryProcInstIdList.Select(a => a = $"'{a.Trim()}'").ToList();
                    ProcInstId_STR = string.Join(',', _ProcInstIdList);
                }
                SqlInsertClip = $"(SELECT SysId,ProcInstId,VerifyStartFolio,VerifyStartProcInstId,ProductLine,ProjectName,ProductModel,TrialManufactureBatch,(CASE WHEN Task4ProblemPositioning IS NOT NULL THEN Task4ProblemPositioning WHEN Task3ProblemPositioning IS NOT NULL THEN Task3ProblemPositioning ELSE ProblemDecide END) AS ProblemPositioning,CreateDate,LineStopDecide FROM ValidationProblemTracking.dbo.ValidationProblemBusinessData WHERE ProcInstId IN({ProcInstId_STR}))";
            }
            else
            {
                SqlInsertClip = $"(SELECT SysId,ProcInstId,VerifyStartFolio,VerifyStartProcInstId,ProductLine,ProjectName,ProductModel,TrialManufactureBatch,(CASE WHEN Task4ProblemPositioning IS NOT NULL THEN Task4ProblemPositioning WHEN Task3ProblemPositioning IS NOT NULL THEN Task3ProblemPositioning ELSE ProblemDecide END) AS ProblemPositioning,CreateDate,LineStopDecide FROM ValidationProblemTracking.dbo.ValidationProblemBusinessData WHERE ProcInstId !='')";
            }

            int startIndex = ((Input.PageIndex - 1) * Input.PageSize) + 1;
            int endIndex = Input.PageSize * Input.PageIndex;

            string sql = @$"SELECT V.[Key],V.ApplicationNumber,V.ProcInstId,V.ApplicantName,V.CurrentStatus,V.ApplicantDate,V.SubmitByID,V.SubmitByName, 
                                   V.VerifyStartFolio,V.VerifyStartProcInstId,V.ProductLine,V.ProjectName,V.ProductModel,V.TrialManufactureBatch,V.ProblemPositioning,V.ApplicantDate,V.LineStopDecide
                                   
                            FROM (SELECT ROW_NUMBER() OVER(ORDER BY V.ApplicantDate DESC) AS RowID,V.* FROM (
                            SELECT vr.SysId AS [Key],TRIM(workflow.ApplicationNumber)AS ApplicationNumber,workflow.ProcInstId,workflow.ApplicantEmployeeNumber AS SubmitByID,TRIM(workflow.CurrentHandler) AS ApplicantName,workflow.CurrentStatus,workflow.SubmitBy AS SubmitByName,
                                   vr.VerifyStartFolio,vr.VerifyStartProcInstId,vr.ProductLine,vr.ProjectName,vr.ProductModel,vr.TrialManufactureBatch,vr.ProblemPositioning,vr.CreateDate AS ApplicantDate,vr.LineStopDecide
                                  
                            FROM {SqlInsertClip} vr 
                            LEFT JOIN VW_Common.dbo.WorkflowApplicationData workflow ON vr.ProcInstId = workflow.ProcInstId) V WHERE {condition}) V 
                            WHERE V.RowID BETWEEN {startIndex} AND {endIndex}";

            list = eFExtension.SqlQuery<ValidationProblemReportFormModel>(dbContext, sql, sqlParameters);

            //赋值流程最早时间
            //if (!string.IsNullOrWhiteSpace(Input.CurrentUser))
            //{
            //    list.ForEach((x) => {
            //        var item = ProcInstIdList.FirstOrDefault(a => a.ProcInstId == x.ProcInstId);
            //        if (item != null)
            //        {
            //            x.ApplicantDate = item.ApproveDate;
            //        }
            //    });
            //}

            return list;
        }

        /// <summary>
        ///返回中试验证问题处理电子流报表主数据
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public List<ValidationProblemReportFormModel> GetValidationProblemReportFormData(ValidationProblemReportConditionModel Input)
        {
            List<ValidationProblemReportFormModel> list = new List<ValidationProblemReportFormModel>();
            List<SqlParameter> sqlParameters = new List<SqlParameter>();
            var eFExtension = new EFExtension();

            string condition = "1=1 ";

            if (!string.IsNullOrWhiteSpace(Input.ProcessFolio))
            {
                condition += $"AND workflow.ApplicationNumber LIKE '%{Input.ProcessFolio}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.VerifyStartFolio))
            {
                condition += $"AND vr.VerifyStartFolio LIKE '%{Input.VerifyStartFolio}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.ProductLine))
            {
                condition += $"AND vr.ProductLine LIKE '%{Input.ProductLine}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.ProjectName))
            {
                condition += $"AND vr.ProjectName LIKE '%{Input.ProjectName}%' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.Applicant))
            {
                condition += $"AND workflow.ApplicantEmployeeNumber = '{Input.Applicant}' ";
            }
            if (!string.IsNullOrWhiteSpace(Input.ApplicantDate))
            {
                string[] timeArr = Input.ApplicantDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND vr.CreateDate >= '{timeArr[0]} 00:00:00' AND vr.CreateDate <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(Input.CurrentStatus))
            {
                condition += $"AND workflow.CurrentStatus = '{Input.CurrentStatus}' ";
            }


            //if (!string.IsNullOrWhiteSpace(input.AssetNo))
            //{
            //    condition += $"AND capitalSub.AssetNo LIKE '%'+@AssetNo+'%' ";
            //    SqlParameter sqlPara = new SqlParameter("@AssetNo", SqlDbType.NVarChar);
            //    sqlPara.Value = input.AssetNo;
            //    sqlParameters.Add(sqlPara);
            //}
            string SqlInsertClip = string.Empty;

            List<WorkflowProcInstIdModel> ProcInstIdList = new List<WorkflowProcInstIdModel>();

            //获取当前用户资产赔偿电子流审批流程记录,去重后联查得到ProcInstId
            string _sql = $"SELECT a.ProcInstId,c.ApplicationNumber,c.ApproveDate,c.ApproverName FROM ValidationProblemTracking.dbo.ValidationProblemBusinessData a LEFT JOIN (SELECT DISTINCT(ApplicationNumber),(SELECT MIN(ApproveDate) FROM VW_Common.dbo.WorkflowApproveData WHERE ApplicationNumber = b.ApplicationNumber AND WorkflowName = '中试验证问题处理电子流')  AS ApproveDate,ApproverName FROM VW_Common.dbo.WorkflowApproveData b WHERE WorkflowName = '中试验证问题处理电子流') c ON c.ApplicationNumber = a.ProcessFolio WHERE ProcInstId !='' AND ApproveDate IS NOT NULL";
            ProcInstIdList = eFExtension.SqlQuery<WorkflowProcInstIdModel>(dbContext, _sql, new List<SqlParameter>());

            //插入当前用户查询业务
            if (!string.IsNullOrWhiteSpace(Input.CurrentUser))
            {
                ProcInstIdList = ProcInstIdList.Where(a => a.ApproverName == Input.CurrentUser).ToList();
                //审批历史ProcInstId
                var ApprovalHistoryProcInstIdList = ProcInstIdList.Select(a => a.ProcInstId).ToList();

                //当前用户工号
                string employeeNumber = Input.CurrentUser.Substring(0, Input.CurrentUser.IndexOf(" "));
                //利用UserID获取当前用户工号LaunchList
                //var EmployeeInfo = userBaseInforDataContext.UserBaseInfor.FirstOrDefault(x => x.UserId == UserId);
                if (!string.IsNullOrWhiteSpace(employeeNumber))
                {
                    //获取发起流程实例
                    _sql = $"SELECT ProcInstId FROM VW_Common.dbo.WorkflowApplicationData WHERE ProcInstId !='' AND WorkflowName='中试验证问题处理电子流' AND ApplicantEmployeeNumber = '{employeeNumber}'";
                    List<WorkflowProcInstIdModel> LaunchList = eFExtension.SqlQuery<WorkflowProcInstIdModel>(dbContext, _sql, new List<SqlParameter>());
                    if (LaunchList.Any())
                    {
                        var LaunchProcInstIdList = LaunchList.Select(a => a.ProcInstId).ToList();
                        ApprovalHistoryProcInstIdList.AddRange(LaunchProcInstIdList);
                        ApprovalHistoryProcInstIdList = ApprovalHistoryProcInstIdList.Distinct().ToList();
                    }
                }

                string ProcInstId_STR = "''";
                if (ApprovalHistoryProcInstIdList.Any())
                {
                    List<string> _ProcInstIdList = ApprovalHistoryProcInstIdList.Select(a => a = $"'{a.Trim()}'").ToList();
                    ProcInstId_STR = string.Join(',', _ProcInstIdList);
                }

                SqlInsertClip = $"(SELECT SysId,ProcInstId,VerifyStartFolio,VerifyStartProcInstId,ProductLine,ProjectName,ProductModel,TrialManufactureBatch,(CASE WHEN Task4ProblemPositioning IS NOT NULL THEN Task4ProblemPositioning WHEN Task3ProblemPositioning IS NOT NULL THEN Task3ProblemPositioning ELSE ProblemDecide END) AS ProblemPositioning,CreateDate,LineStopDecide FROM ValidationProblemTracking.dbo.ValidationProblemBusinessData WHERE ProcInstId IN({ProcInstId_STR}))";
            }
            else
            {
                SqlInsertClip = $"(SELECT SysId,ProcInstId,VerifyStartFolio,VerifyStartProcInstId,ProductLine,ProjectName,ProductModel,TrialManufactureBatch,(CASE WHEN Task4ProblemPositioning IS NOT NULL THEN Task4ProblemPositioning WHEN Task3ProblemPositioning IS NOT NULL THEN Task3ProblemPositioning ELSE ProblemDecide END) AS ProblemPositioning,CreateDate,LineStopDecide FROM ValidationProblemTracking.dbo.ValidationProblemBusinessData WHERE ProcInstId !='')";
            }

            string sql = @$"SELECT vr.SysId AS [Key],TRIM(workflow.ApplicationNumber)AS ApplicationNumber,workflow.ProcInstId,workflow.ApplicantEmployeeNumber AS SubmitByID,TRIM(workflow.CurrentHandler) AS ApplicantName,workflow.CurrentStatus,workflow.SubmitBy AS SubmitByName,
                                   vr.VerifyStartFolio,vr.VerifyStartProcInstId,vr.ProductLine,vr.ProjectName,vr.ProductModel,vr.TrialManufactureBatch,vr.ProblemPositioning,vr.CreateDate AS ApplicantDate,vr.LineStopDecide

                            FROM {SqlInsertClip} vr 
                            LEFT JOIN VW_Common.dbo.WorkflowApplicationData workflow ON vr.ProcInstId = workflow.ProcInstId 
                            WHERE {condition}";


            list = eFExtension.SqlQuery<ValidationProblemReportFormModel>(dbContext, sql, sqlParameters);

            return list;
        }

        /// <summary>
        /// 新增中试验证问题处理电子流业务数据
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<int> AddValidationProblemBusinessData(ValidationProblemBusinessDataModel Input)
        {
            var item = await dbContext.ValidationProblemBusinessData.FirstOrDefaultAsync(a => a.ProcInstId == Input.ProcInstId);
            if (item != null)
            {
                dbContext.ValidationProblemBusinessData.Remove(item);
            }

            dbContext.ValidationProblemBusinessData.Add(Input);

            return await dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 获取启动单数据
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public (List<LaunchOrderModel>,int) GetLaunchOrderDataList(LaunchOrderConditionModel Input) 
        {
            List<LaunchOrderModel> LaunchOrderList = new List<LaunchOrderModel>();
            int SkipCount = (Input.PageIndex - 1) * Input.PageSize;
            var data = workflowCommonDataContext.ApplicationData.WhereIf(!string.IsNullOrWhiteSpace(Input.Keyword), a => a.ApplicationNumber.Contains(Input.Keyword)).Where(a => a.WorkflowName == "中试验证启动表" && (a.CurrentStatus == "待验证启动审批（试制工程师）" || a.CurrentStatus == "流程结束")).ToList();
            var ReportFormDataList = dbContext.LaunchVerifyReport.WhereIf(!string.IsNullOrWhiteSpace(Input.Keyword), a => a.Folio.Contains(Input.Keyword)).ToList();

            var result = from a in data
                         join b in ReportFormDataList on a.ApplicationNumber.Trim() equals b.Folio.Trim() into c
                         from b in c.DefaultIfEmpty()
                         select new ApplicationDataModel {
                             ID = a.ID,
                             WorkflowName = a.WorkflowName,
                             ApplicationNumber = a.ApplicationNumber,
                             ProcInstId = a.ProcInstId,
                             CurrentStatus = a.CurrentStatus,
                             CurrentHandler = a.CurrentHandler,
                             MobilePhone = a.MobilePhone,
                             ApplicantEmployeeNumber = a.ApplicantEmployeeNumber,
                             ApplicantName = a.ApplicantName,
                             DepartmentCode = a.DepartmentCode,
                             DepartmentName = a.DepartmentName,
                             FormData = a.FormData,
                             MailBody = a.MailBody,
                             //CreatedDate = b.CreaterTime.Value,
                             CreatedDate = b == null ? a.CreatedDate : b.CreaterTime.Value,
                             SubmitBy = a.SubmitBy,
                             ScopeID = a.ScopeID
                         };

            var aa = result.ToList();
            int count = data.Count();
            var list = result.OrderByDescending(a => a.CreatedDate).Skip(SkipCount).Take(Input.PageSize).ToList();

            if (list.Any()) 
            {
                list.ForEach((x) => {
                    JObject Json = (JObject)JsonConvert.DeserializeObject(x.FormData);
                    LaunchOrderModel item = new LaunchOrderModel();
                    item.sysId = x.ID.ToString();
                    item.folio = x.ApplicationNumber;
                    item.subject = Json["formHeader"]["subject"].ToString();
                    item.procInstId = x.ProcInstId;
                    item.applicant = x.SubmitBy;
                    item.applicantId = x.ApplicantEmployeeNumber;
                    item.applicationDate = x.CreatedDate;
                    item.productLine = Json["productLine"].ToString();
                    item.projectName = Json["projectName"].ToString();
                    item.projectCode = Json["projectCode"].ToString();
                    item.productModelNumber = Json["productModelNumber"].ToString();
                    item.batchNumber = Json["batchNumber"].ToString();
                    item.erpDeviceInfoDetaiList = JsonConvert.DeserializeObject<List<ERPDeviceInfoDetail>>(Json["erpDeviceInfo"].ToString());
                    LaunchOrderList.Add(item);
                });
            }
            return (LaunchOrderList, count);
        }

        /// <summary>
        /// 根据ProcInstId获取启动单数据
        /// </summary>
        /// <param name="procInstId"></param>
        /// <returns></returns>
        public List<LaunchOrderModel> GetProcInstIdLaunchOrderDataList(string procInstId) 
        {
            List<LaunchOrderModel> LaunchOrderList = new List<LaunchOrderModel>();
            var data = workflowCommonDataContext.ApplicationData.Where(a => a.WorkflowName == "中试验证启动表" && a.ProcInstId == procInstId && (a.CurrentStatus == "待验证启动审批（试制工程师）" || a.CurrentStatus == "流程结束")).ToList();
            var ReportFormDataList = dbContext.LaunchVerifyReport.Where(a=>a.ProcInstId == procInstId).ToList();

            var result = from a in data
                         join b in ReportFormDataList on a.ApplicationNumber.Trim() equals b.Folio.Trim() into c
                         from b in c.DefaultIfEmpty()
                         select new ApplicationDataModel
                         {
                             ID = a.ID,
                             WorkflowName = a.WorkflowName,
                             ApplicationNumber = a.ApplicationNumber,
                             ProcInstId = a.ProcInstId,
                             CurrentStatus = a.CurrentStatus,
                             CurrentHandler = a.CurrentHandler,
                             MobilePhone = a.MobilePhone,
                             ApplicantEmployeeNumber = a.ApplicantEmployeeNumber,
                             ApplicantName = a.ApplicantName,
                             DepartmentCode = a.DepartmentCode,
                             DepartmentName = a.DepartmentName,
                             FormData = a.FormData,
                             MailBody = a.MailBody,
                             //CreatedDate = b.CreaterTime.Value,
                             CreatedDate = b == null ? a.CreatedDate : b.CreaterTime.Value,
                             SubmitBy = a.SubmitBy,
                             ScopeID = a.ScopeID
                         };

            var aa = result.ToList();
            int count = data.Count();
            var list = result.OrderByDescending(a => a.CreatedDate).ToList();

            if (list.Any())
            {
                list.ForEach((x) => {
                    JObject Json = (JObject)JsonConvert.DeserializeObject(x.FormData);
                    LaunchOrderModel item = new LaunchOrderModel();
                    item.sysId = x.ID.ToString();
                    item.folio = x.ApplicationNumber;
                    item.subject = Json["formHeader"]["subject"].ToString();
                    item.procInstId = x.ProcInstId;
                    item.applicant = x.SubmitBy;
                    item.applicantId = x.ApplicantEmployeeNumber;
                    item.applicationDate = x.CreatedDate;
                    item.productLine = Json["productLine"].ToString();
                    item.projectName = Json["projectName"].ToString();
                    item.projectCode = Json["projectCode"].ToString();
                    item.productModelNumber = Json["productModelNumber"].ToString();
                    item.batchNumber = Json["batchNumber"].ToString();
                    item.erpDeviceInfoDetaiList = JsonConvert.DeserializeObject<List<ERPDeviceInfoDetail>>(Json["erpDeviceInfo"].ToString());
                    LaunchOrderList.Add(item);
                });
            }
            return LaunchOrderList;
        }

        /// <summary>
        /// 邮件知会
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool SendEmailNotification(InformInformation info) 
        {
            try
            {
                if (info != null) 
                {
                    List<EmailParameter> emaiList = new List<EmailParameter>();
                    info.UserIDList.ForEach((x) => {
                        emaiList.Add(new EmailParameter
                        {
                            ProcInstId = info.ProcInstId,
                            Subject = info.Subject,
                            FunctionId = info.FunctionId,
                            DocumentDistributionUserID = x,
                            ViteFormUrl = info.ViteFormUrl,
                        }); ;
                    });

                    //发送邮件
                    if (emaiList.Any())
                    {
                        EmailSending(emaiList);
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 发送邮件通知
        /// </summary>
        /// <param name="list"></param>
        public async void EmailSending(List<EmailParameter> list)
        {
            if (list.Any())
            {
                //用户ID
                List<string> UserIdList = list.Select(a => a.DocumentDistributionUserID).ToList();
                var emailList = userBaseInforDataContext.UserBaseInfor.Where(a => UserIdList.Contains(a.UserId)).ToList();
                var html = await RazorTemplateEngine.RenderAsync("~/Pages/EmailTemplates/VehicleMaintenance/InvalidEmailSendingIndex.cshtml");
                var TemporaryProcessDocumentFrontEndHost = configuration.GetSection("ValidationProblemTracking").Value;
                html = html.Replace("[ViteFormUrl]", TemporaryProcessDocumentFrontEndHost);

                if (!string.IsNullOrWhiteSpace(html))
                {
                    var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;

                    foreach (var x in list)
                    {
                        var url = $"{CommonServiceHost}{encyptUserInfo}?userID={x.DocumentDistributionUserID}&functionID={x.FunctionId}&procInstID={x.ProcInstId}";
                        //获取加密字符串
                        var response = await HttpHelper.GetAsync<string>(url);

                        string templateData = html;
                        templateData = templateData.Replace("\r\n", "");
                        templateData = templateData.Replace("\\", "");
                        templateData = templateData.Replace("${subject}", x.Subject);
                        templateData = templateData.Replace("${_Para}", response);
                        templateData = templateData.Replace("[ViteUrl]", x.ViteFormUrl);

                        //配置邮箱参数
                        MailSendModel mailSend = new MailSendModel();
                        mailSend.mailID = 0;
                        mailSend.mailFrom = configuration.GetSection("ApproverSendToEmail").Value;
                        //mailSend.mailTo = "邮箱";
                        mailSend.mailSubject = x.Subject;
                        mailSend.mailBody = templateData;
                        mailSend.isHtml = 1;
                        mailSend.mailStatus = 0;

                        //发送邮件路径
                        var url2 = $"{CommonServiceHost}{MailSendUrl}";

                        //获取人员邮箱
                        if (!string.IsNullOrWhiteSpace(x.DocumentDistributionUserID))
                        {
                            string[] userIdArrar = x.DocumentDistributionUserID.Split(';');

                            foreach (var y in userIdArrar)
                            {
                                var item = emailList.FirstOrDefault(a => a.UserId == y);
                                if (item == null)
                                {
                                    continue;
                                }

                                mailSend.mailTo = item.Email;
                                mailSend.createdDate = DateTime.Now;
                                if (!string.IsNullOrWhiteSpace(mailSend.mailTo))
                                {
                                    await HttpHelper.PostAsync<int>(url2, JsonConvert.SerializeObject(mailSend));
                                }
                            };
                        }
                    };
                }
            }
        }

    }
}
